<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10 paddingBottom20">
        <div class="mainor_form">
          <div class="mainor_te">
            <el-button @click="pldeliver" class="mainor_tea">批量同步</el-button>
            <router-link to="/order/batch/record"><el-button>操作记录</el-button></router-link>
          </div>
          <div class="mainsu_te">
            <el-checkbox v-model="type"
              >同步修改市场价</el-checkbox
            >
            <el-tooltip class="item" effect="dark" placement="top">
              <div slot="content">
                勾选后修改商品实时单价并保存，<br />系统会自动同步修改商品的市场价！
              </div>
              <svg aria-hidden="true" class="navbar_svg" width="16" height="16">
                <use xlink:href="#icon-summary_question" />
              </svg>
            </el-tooltip>
          </div>
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="70px"
          >
            <el-form-item label="配送日期" prop="send_time">
              <el-date-picker
                v-model="form.send_time"
                type="date"
                class="time220"
                :editable="false"
                placeholder="配送日期"
                value-format="yyyy-MM-dd"
                :clearable="false"
              />
            </el-form-item>
            <el-form-item label="商品分类" prop="select" class="wid220">
              <el-cascader
                v-model="form.category_id"
                :options="options"
                :props="defaultProps"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="商品" prop="name">
              <el-input
                v-model.trim="form.name"
                placeholder="商品"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <el-form-item label="标品" prop="is_standard">
              <el-select
                v-model.trim="form.is_standard"
                placeholder="标品"
                class="wid220"
              >
                <el-option label="所有" value=""></el-option>
                <el-option
                  v-for="(is_standard_list, index) in list.is_standard_list"
                  :key="index"
                  :label="is_standard_list"
                  :value="parseInt(index)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="时价" prop="current_price">
              <el-select
                v-model.trim="form.current_price"
                placeholder="时价"
                class="wid220"
              >
                <el-option label="所有" value=""></el-option>
                <el-option
                  v-for="(current_price_list, index) in list.current_price_list"
                  :key="index"
                  :label="current_price_list"
                  :value="parseInt(index)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                class="reset marginLeft10"
                type="primary"
                @click="
                  $refs['userListFrom'].resetFields(),
                    (form.name = ''),
                    (form.name = '')
                "
                >重置</el-button
              >
              <el-button
                type="primary"
                @click="getArticleList"
                :loading="listLoading"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="main_num boxdq marginTop10">
          <div class="main_num_l box">
            <p>
              <em
                >说明：已完成状态前所有订单可批量同步当前最新单价，也可修改当前最新单价，保存时会更新订单价格；</em
              >
            </p>
          </div>
        </div>
        <div class="main_table marginTop10" style="min-height: 550px">
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="list.list"
            element-loading-text="加载中"
            fit
            border
            highlight-current-row
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" />
            <el-table-column label="商品名称" prop="name" width="150">
              <template slot-scope="scope"
                >{{ scope.row.goods.name }}【{{
                  scope.row.spu_name.title
                }}】</template
              >
            </el-table-column>
            <el-table-column label="单位" prop="spu_unit.title" />
            <el-table-column label="近一次采购价" prop="purchase_price" />
            <el-table-column label="下单人数" prop="count" />
            <el-table-column
              label="配送单价"
              prop=""
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <div class="mainus_pe">
                  <div v-if="!scope.row.show">
                    {{ scope.row.price }}
                  </div>
                  <div v-else class="boxnr">
                    <el-input
                      v-focus="'price'+scope.$index"
                      v-model="scope.row.price"
                      placeholder="配送单价"
                      class="wid80"
                    ></el-input>
                  </div>
                </div>
              </template>
            </el-table-column>
             <el-table-column label="市场价" prop="market_price" />
            <el-table-column
              label="管理操作"
              align="center"
              fixed="right"
              width="180"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <el-link type="warning" @click="order_savePrice(scope.row.market_price,scope.$index,true)">同步</el-link>
                <el-link type="primary" @click="bcClick(scope.$index)">{{ scope.row.show?'保存':'修改' }}</el-link>
                <el-link
                  type="danger"
                  v-if="scope.row.show"
                  @click="scope.row.show=!scope.row.show,orderList_pricing()"
                  >取消</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 批量同步 -->
        <el-dialog
          :title="'已选择' + selectArr.length + '个商品，确定全部同步吗？'"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          @close="close"
          :visible.sync="addedFormVisible"
          class="main_dialog dialog450"
        >
          <el-progress
            :text-inside="true"
            :stroke-width="15"
            :percentage="percent"
            status="success"
            color="#E47C02"
            style="width: 60%"
          ></el-progress>
          <div class="progress_list">
            <template v-for="(percent_list,index) in reverseSum">
              <template v-if="index<5">
                <p v-if="percent_list.type==1" :key="index">商品id:{{ percent_list.order_id }}，同步已成功</p>
                <p v-else class="progress_list_red" :key="index">商品id:{{ percent_list.order_id }}，同步失败</p>
              </template>
            </template>
            <p v-if="percent==100" class="progress_list_su">同步已经完成请关闭弹框!</p>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  orderList_pricing,
  order_savePrice,
  orderList_batchDispatchPricing
} from "@/api/order/orderBatch";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { parseTime, recursion, category } from "@/utils/index";

export default {
  directives: {
    // 聚焦元素
    focus: {
      inserted(el) {
        el.querySelector("input").focus();
      },
    },
  },
  computed: {
    ...mapGetters(["avatar"]),
    reverseSum() {
        return this.percent_list.reverse();
    }
  },
  components: {},
  data() {
    return {
      // 列表数据
      list: {
        list: [],
      },
      listLoading: false,
      // 搜索
      form: {
        pid: "",
        category_id: [],
        send_time: parseTime(new Date(), "{y}-{m}-{d}"),
        name: "",
        is_standard:null,
        current_price:null
      },
      type:true,
      // 分类
      options: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
        value: "id",
        checkStrictly: true,
      },
      offsetParent: true,
      // 批量同步
      percent_gs:0,
      percent:0,
      percent_list:[],
      addedFormVisible: false,
      // 全选
      selectArr: [],
    };
  },
  mounted() {
    window.Echo.channel("batchDispatchPricing."+this.avatar.company_id).listen(
      "BatchDispatchPricingEvent",
      (e) => {
        this.percent_gs=parseInt(this.percent_gs)+1
        if(this.percent_gs/this.selectArr.length*100>=100){
          this.percent=100
          return
        }
        this.percent=this.percent_gs/this.selectArr.length?parseInt(this.percent_gs/this.selectArr.length*100):0
        if(e.notice.msg=='ok'){
          this.percent_list.push({num:this.percent,type:1,order_id:e.notice.goods_spu_id})
        }else{
          this.percent_list.push({num:this.percent,type:2,order_id:e.notice.goods_spu_id})
        }
      }
    );
  },
  created() {
    // 列表
    this.orderList_pricing();
  },
  methods: {
    // 关闭清空表单
    close() {
      this.percent=0
      this.percent_gs=0
      this.percent_list=[]
      this.orderList_pricing();
      // this.$refs["userListFrom1"].clearValidate();
    },
    // 监听全选
    handleSelectionChange(val) {
      this.selectArr = [];
      val.map((item) => {
        this.selectArr.push({ id: item.id,price: item.market_price });
      });
    },
    // 修改
    bcClick(index){
      if(this.list.list[index].show){
        this.order_savePrice(this.list.list[index].price,index)
      }
      this.list.list[index].show=!this.list.list[index].show
      setTimeout(()=>{
        if(this.$refs['price'+index]){
          this.$refs['price'+index].focus();
        }
      }, 200);
    },
    order_savePrice(price,index,type){
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, {
                id: this.list.list[index].id,
                price: price,
                synchronous_price:this.type?1:0,
                send_time: this.form.send_time
              })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: this.list.list[index].id,price: price,synchronous_price:this.type?1:0,send_time: this.form.send_time }
      );
      order_savePrice(data).then((res) => {
        if (res.errcode == 0) {
          if(type){
            this.$message({
              message: "同步成功",
              type: "success",
            });
          }else{
            this.$message({
              message: "修改成功",
              type: "success",
            });
          }
          this.orderList_pricing();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 批量同步
    setupmine() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { ids: JSON.stringify(this.selectArr),send_time: this.form.send_time,synchronous_price:this.type?1:0, }
      );
      orderList_batchDispatchPricing(data).then((res) => {
        this.addedFormVisible = true;
      });
    },
    pldeliver(){
      if (this.selectArr.length != 0) {
        this.setupmine();
      } else {
        this.$message.error("请勾选商品");
      }
    },
    // 搜索
    getArticleList() {
      this.orderList_pricing();
    },
    // 列表
    orderList_pricing() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      orderList_pricing(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.options = recursion(res.data.categoryList, true);
          res.data.list.map((e) => {
            e.show = false;
          });
          // this.type=res.data.type==1?true:false
          this.list = res.data;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.pid = form.category_id[0] ? form.category_id[0] : "";
      form.category_id = category(form.category_id);

      return form;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: calc(100% - 180px);
  }

  .main_dialog {
    .progress_list{
      margin-top: 10px;
      p{
        height:24px;
        line-height: 24px;
      }
      .progress_list_red{
        color: red;
      }
      .progress_list_su{
        color: #03A98E;
      }
    }
  }
}
</style>
